package com.nd.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nd.common.result.ResultUtils;
import com.nd.common.utils.EmptyUtils;
import com.nd.entity.Cart;
import com.nd.entity.Type;
import com.nd.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liruirui
 * @since 2024-12-25
 */
@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    ICartService service;

    /**
     * 查询购物清单
     * @param deskId
     * @return
     */
    @GetMapping("/")
    public Object getList(Integer deskId){
        List<Cart> list = service.getListByDeskId(deskId);
        return ResultUtils.returnDataSuccess(list);
    }


    /**
     * 删除
     * @param deskId
     * @return
     */
    @DeleteMapping("/")
    public Object del(Integer deskId){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("desk_id",deskId);
        if(service.remove(queryWrapper)){
            return ResultUtils.returnSuccess();
        } else {
            return ResultUtils.returnFail("删除失败");
        }
    }



    /**
     * 添加
     * @param t
     * @return
     */
    @PostMapping("/")
    public Object add(@RequestBody Cart t){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("desk_id",t.getDeskId());
        queryWrapper.eq("product_id",t.getProductId());

        //若对象不为空--查到了---修改数量，+1
        Cart one = service.getOne(queryWrapper);
        if(EmptyUtils.isNotEmpty(one)){
            //修改数量(在原来的基础上+1)
            one.setNum(one.getNum()+t.getNum());
            if(one.getNum()<=0){ //当数数量减到0了，执行删除
                //执行删除
                if (service.removeById(one.getId())) {
                    return ResultUtils.returnSuccess();
                } else {
                    return ResultUtils.returnFail("删除失败");
                }
            }else {
                //执行修改
                if (service.updateById(one)) {
                    return ResultUtils.returnSuccess();
                } else {
                    return ResultUtils.returnFail("修改失败");
                }
            }
        }else{ //没查到，新增
            //增加一条数据
            if(service.save(t)){
                return ResultUtils.returnSuccess();
            }else{
                return ResultUtils.returnFail("添加失败");
            }
        }
    }

}
